package com.suse.service.community.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.suse.common.util.core.StringUtil;
import com.suse.common.util.core.UUIDUtil;
import com.suse.common.util.mail.MailUtil;
import com.suse.service.community.constant.UserConstant;
import com.suse.service.community.entity.LoginTicket;
import com.suse.service.community.entity.User;
import com.suse.service.community.mapper.LoginTicketMapper;
import com.suse.service.community.mapper.UserMapper;
import com.suse.service.community.service.UserService;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户业务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-29 15:37
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private LoginTicketMapper loginTicketMapper;

    @Override
    public User getUserById(int id) {
        return userMapper.selectById(id);
    }

    /**
     * 注册用户
     * @return 返回信息
     */
    @Override
    public Map<String,Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtil.isNull(user)) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtil.isEmpty(user.getUsername())) {
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if (StringUtil.isEmpty(user.getPassword())) {
            map.put("passwordMsg","密码不能为空！");
            return map;
        }
        if (StringUtil.isEmpty(user.getEmail())) {
            map.put("emailMsg","邮箱不能为空！");
            return map;
        }
        // 验证账号
        User dbUser = userMapper.selectByName(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            map.put("usernameMsg","该账号已存在！");
            return map;
        }
        // 验证邮箱
        dbUser = userMapper.selectByEmail(user.getEmail());
        if (ObjectUtil.isNotNull(dbUser)) {
            map.put("emailMsg","该邮箱已被注册！");
            return map;
        }
        // 注册用户
        user.setSalt(UUIDUtil.generateUUID().substring(0,5));
        // md5 加盐加密
        user.setPassword(DigestUtil.md5Hex16(user.getPassword() + user.getSalt()));
        // 注册默认普通用户
        user.setType(0);
        // 默认未激活
        user.setStatus(0);
        // 激活码
        user.setActivationCode(UUIDUtil.generateUUID());
        // 头像
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", RandomUtil.randomInt(0,1000)));
        // 注册时间
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        // 发送激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        String url = "http://localhost:8080/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation", context);
        MailUtil.sendMail(user.getEmail(),"激活账号",content);
        // 返回信息
        return map;
    }

    @Override
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return UserConstant.ACTIVATION_REPEAT;
        }
        if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId,1);
            return UserConstant.ACTIVATION_SUCCESS;
        }
        return UserConstant.ACTIVATION_FAIL;
    }

    @Override
    public Map<String, Object> login(User user,int expireSeconds) {
        String username = user.getUsername();
        String password = user.getPassword();
        HashMap<String, Object> map = new HashMap<>();
        // 空值判断
        if (StringUtil.isEmpty(username)) {
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if (StringUtil.isEmpty(password)) {
            map.put("passwordMsg","密码不能为空！");
            return map;
        }
        // 验证账号
        User dbUser = userMapper.selectByName(username);
        if (ObjectUtil.isNull(dbUser)) {
            map.put("usernameMsg","该账号不存在！");
            return map;
        }
        if (dbUser.getStatus() == 0) {
            map.put("usernameMsg","该账号未激活！");
            return map;
        }
        // 验证密码
        password = DigestUtil.md5Hex16(password + dbUser.getSalt());
        if (StringUtil.isNotEquals(password,dbUser.getPassword())) {
            map.put("passwordMsg","密码不正确！");
            return map;
        }
        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        // 设置用户ID
        loginTicket.setUserId(dbUser.getId());
        // 生成登录凭证随机字符串
        loginTicket.setTicket(UUIDUtil.generateUUID());
        // 默认有效
        loginTicket.setStatus(1);
        // 默认登录凭证有效期 3 天
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expireSeconds * 1000));
        // 保存到数据库
        loginTicketMapper.insert(loginTicket);
        // 返回登录凭证随机字符串
        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
        // 修改登录凭证为无效状态
        loginTicketMapper.updateStatus(ticket,0);
    }

    @Override
    public LoginTicket getLoginTicketByTicket(String ticket) {
        return loginTicketMapper.selectByTicket(ticket);
    }

    @Override
    public boolean updateHeader(int id, String headerUrl) {
        int row = userMapper.updateHeader(id, headerUrl);
        return row == 1;
    }

    @Override
    public User getByName(String name) {
        return userMapper.selectByName(name);
    }

}
